<?php

class Model_News
{
    /*
     * 新闻表
     * @var Zend_Db_Table
     */
    protected $_newsTable;
    /**
     * 新闻类别表
     * @var Zend_Db_Table
     */
    protected $_newsCategoryTable;

    /**
     * 新闻数据
     * @var array
     */
    protected $_data;

    /**
     * 新闻类别数据
     * @var array
     */
    protected $_categoryData;

    /**
     * 构造方法
     *
     * 初始化一条新闻
     *
     * @param array $options 新闻数据
     * @return void
     */
    public function __construct(array $options = null)
    {
        if (is_array($options)) {
            $this->_data = $options;
        }
    }

    /**
     * __set() 设置一条新闻的属性值
     *
     * @param string $name
     * @param mixed  $value
     */
    public function __set($name, $value)
    {
        $this->_data[$name] = $value;
    }

    /**
     * __get() 返回一条新闻的属性值
     *
     * @param  string $name
     * @return mixed
     */
    public function __get($name)
    {
        if(isset($this->_data[$name])){
            return $this->_data[$name];
        }
        trigger_error('属性 ' . $name . '" 不存在', E_USER_NOTICE);
        return NULL;
    }

    /**
     * 设置新闻信息
     *
     * @param array $data 新闻信息
     * @return News
     */
    public function setData(array $data)
    {
        if (is_array($data)) {
            $this->_data = array_merge((array)$this->_data,$data);
        }
        return $this;
    }

    /**
     * 获取新闻信息
     *
     * @param string $name
     * @return mixed
     */
    public function getData($name = null)
    {
        if($name === null){
            return $this->_data;
        }elseif (is_string($name)&&isset($this->_data[$name])){
            return $this->_data[$name];
        }
        return NULL;
    }


    /**
     * 设置新闻类别信息
     *
     * @param array $data 新闻类别信息
     * @return News
     */
    public function setCategoryData(array $data)
    {
        if (is_array($data)) {
            $this->_categoryData = array_merge((array)$this->_categoryData,$data);
        }
        return $this;
    }

    /**
     * 获取新闻类别信息
     *
     * @param string $name
     * @return mixed
     */
    public function getCategoryData($name = null)
    {
        if($name === null){
            return $this->_categoryData;
        }elseif (is_string($name)&&isset($this->_categoryData[$name])){
            return $this->_categoryData[$name];
        }
        return NULL;
    }

    /**
     * 设置新闻表
     *
     * @param mixed $dbTable
     * @return News
     */
    public function setNewsTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_newsTable = $dbTable;
        return $this;
    }

    /**
     * 设置新闻类别表
     *
     * @param mixed $dbTable
     * @return News
     */
    public function setNewsCategoryTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_newsCategoryTable = $dbTable;
        return $this;
    }

    /**
     * 获取新闻表
     *
     * @return Zend_Db_Table
     */
    public function getNewsTable()
    {
        if(null === $this->_newsTable){
            $this->setNewsTable('Model_DbTable_News');
        }
        return $this->_newsTable;
    }

    /**
     * 获取新闻类别表对象
     *
     * @return Zend_Db_Table
     */
    public function getNewsCategoryTable()
    {
        if(null === $this->_newsCategoryTable){
            $this->setNewsCategoryTable('Model_DbTable_NewsCategory');
        }
        return $this->_newsCategoryTable;
    }

    /**
     * 保存新闻
     *
     * @param  array $data
     * @return mixed
     */
    public function saveNews(array $data = array())
    {
        $id = $this->getData('id');
        if(!empty($data)){
            $this->setData($data);
        }
        $fields = $this->getNewsTable()->info(Zend_Db_Table_Abstract::COLS);
        foreach ($this->_data as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($this->_data[$field]);
            }
        }
        unset($this->_data['id']);
        if(empty($this->_data['title'])){
            throw new Exception('请指定文章的标题！');
        }
        if(empty($this->_data['cid'])){
            throw new Exception('请指定文章的类别！');
        }
        if(empty($this->_data['source'])){
            $this->_data['source'] = '未知';
        }
        if(empty($this->_data['author'])){
            $this->_data['author'] = '佚名';
        }
        if(null === $id){
            $this->_data['dateline'] = time();
            $this->_data['ip'] = Hm_Util::getip();
            return $this->getNewsTable()->insert($this->_data);
        }else{
            $this->_data['last_dateline'] = time();
            $this->_data['last_ip'] = Hm_Util::getip();
            return $this->getNewsTable()->update($this->_data,array('id = ?'=>$id));
        }
    }

    /**
     * 保存新闻类别
     *
     * @param  array $data
     * @return mixed
     */
    public function saveNewsCategory(array $data = array())
    {
        $id = $this->getCategoryData('id');
        if(!empty($data)){
            $this->setCategoryData($data);
        }
        $fields = $this->getNewsCategoryTable()->info(Zend_Db_Table_Abstract::COLS);
        foreach ($this->_categoryData as $field => $value) {
            if (!in_array($field, $fields)) {
                unset($this->_categoryData[$field]);
            }
        }
        unset($this->_categoryData['id']);
        if(null === $id){
            $this->getNewsCategoryTable()->insert($this->_categoryData);
        }else{
            $this->getNewsCategoryTable()->update($this->_categoryData,array('id = ?'=>$id));
        }
    }

    /**
     * 获取一条新闻
     *
     * @param int $id
     * @return News
     */
    public function getNewsById($id)
    {
        $result = $this->getNewsTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $this->_data = $row->toArray();
        return $this;
    }

    /**
     * 获取一条新闻类别
     *
     * @param int $id
     * @return News
     */
    public function getNewsCategoryById($id)
    {
        $result = $this->getNewsCategoryTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $this->_categoryData = $row->toArray();
        return $this;
    }

    /**
     * 根据条件获取新闻条数
     *
     * @param array $where 必需为专有数组，键值对形式如下：
     * array('favorite_color = ?' => 'yellow',
     * 		 'id IN(?)' => array(1, 2, 3),
     * 		 'xydream_num > ?'=>'1');
     * @return int
     */
    public function count($where)
    {
        $table = $this->getNewsTable();
        $select = $table->select()->from($table->info('name'), 'COUNT(*) AS xydream_count');
        foreach ($where as $key => $value) {
            $select->where($key, $value);
        }
        $select->limit(1);
        return $table->fetchRow($select)->xydream_count;
    }

    /**
     * 获取新闻列表,构建select
     *
     * @param  array $where  形式为(fieldName,  and/Or, compare, value)
     * @param  array $order  形式为(fieldName, order)
     * @return  mixed $select     *
     */
    public function getNewsList(Array $where = array(), Array $order = array(array('id','DESC')))
    {
        $select = $this->getNewsTable()->select();
        foreach ($where AS $w){
	        if ($w[1] == 'or') {
	        	$select->orWhere($w[0] . $w[2] . "?", $w[3]);
	        } else {
	            $select->where($w[0] . $w[2] . "?", $w[3]);
	        }
	    }
	    foreach ($order as $o) {
	    	$select->order($o[0] . " " . $o[1]);
	    }
	    return $select;
    }

    /**
     * 将类别的Id转换为名称
     *
     * @param int $id
     * @return string
     */
    public function categoryId2Name($id)
    {
        $category = $this->getNewsCategoryById($id);
        return $category->name;
    }

    /**
     * 获取新闻类别列表
     *
     * @return Zend_Db_Table_Rowset_Abstract 列表结果集
     */
    public function getCategoryList()
    {
        return $this->getNewsCategoryTable()->fetchAll('1')->toArray();
    }

    /**
     * 新闻数据转换为数组
     *
     * @return array
     */
    public function toArray()
    {
        return (array)$this->_data;
    }
}